package recover

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"payme3000/framework/errorx"
)

type PanicHandle func(err any)

var (
	// defaultHandle is called for recovering from panics spawned internally to the library (and thus
	// not recoverable by the caller's goroutine).
	defaultHandle = func(err any) {
		errorx.Catch(context.Background(), err, 3)
		_ = logx.Close()
	}
)

func WithRecover(fn func(), opts ...any) {
	defer func() {
		var handle PanicHandle
		for _, opt := range opts {
			switch _opt := opt.(type) {
			case PanicHandle:
				handle = _opt
			}
		}

		if handle == nil {
			handle = defaultHandle
		}

		if err := recover(); err != nil && handle != nil {
			handle(err)
		}
	}()

	fn()
}
